package com.ruoyi.system.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ruoyi.asms.controller.AsmsFaultAssetController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.vo.DeptUserVo;
import com.ruoyi.common.core.domain.vo.DoImportDeptUserInfoVo;
import com.ruoyi.common.core.domain.vo.ImportDeptUserInfoVo;
import com.ruoyi.common.core.domain.vo.UserDeptName;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.domain.SysUserNoticeInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;

import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.common.wx.config.WxMaConfiguration;
import com.ruoyi.system.domain.SysNotify;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends com.ruoyi.common.core.web.controller.BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleDeptService roleDeptService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ReUsingService reUsingService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private ISysNotifyService notifyService;
    @Autowired
    private TokensService tokenService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ISysUserConfigService userConfigService;
   // @Autowired
  //  private RemoteAsmsService remoteAsmsService;

    private AsmsFaultAssetController faultAssetController;

    /**
     * 获取用户列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list")
    @ApiOperation("获取用户列表")
    public com.ruoyi.common.core.web.page.TableDataInfo list(UserListVo vo) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (vo.getNickName() != null) {
            wrapper.like(SysUser.NICK_NAME, vo.getNickName());
        }
        if (vo.getPhonenumber() != null) {
            wrapper.like(SysUser.PHONENUMBER, vo.getPhonenumber());
        }
        if (vo.getStatus() != null) {
            wrapper.eq(SysUser.STATUS, vo.getStatus());
        }
        if (vo.getDeptId() != null) {
            wrapper.eq(SysUser.DEPT_ID, vo.getDeptId());
        }
        //系统管理员查看所有用户、部门负责人查看当前部门及下级部门的用户
        Set<Long> userCanLookDeptIds = tokenService.getUserCanLookDeptIds();
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && userCanLookDeptIds != null
                && userCanLookDeptIds.size() > 0) {
            wrapper.in(SysUser.DEPT_ID, userCanLookDeptIds);
        }
        wrapper.orderByDesc(SysUser.CREATE_TIME);
        startPage();
        List<SysUser> list = userService.list(wrapper);

        //构造用户与角色关系的map，提高查询速度
        HashMap<Long, HashSet<Long>> userIdRoleIdMap = new HashMap<>();
        HashSet<Long> roleIds = new HashSet<>();
        List<SysUserRole> userRoleList = sysUserRoleService.list();
        Long userId = userRoleList.get(0).getUserId();
        int judge = 0;
        for (SysUserRole userRole : userRoleList) {
            judge++;
            if (!userId.equals(userRole.getUserId())) {
                HashSet<Long> temp = new HashSet<>(roleIds);
                userIdRoleIdMap.put(userId, temp);
                userId = userRole.getUserId();
                roleIds.clear();
                roleIds.add(userRole.getRoleId());
                //若循环执行到了最后，把最后一条key-value加入Map
                if (judge == userRoleList.size())
                    userIdRoleIdMap.put(userId, roleIds);
                continue;
            }
            roleIds.add(userRole.getRoleId());
            //若循环执行到了最后，把最后一条key-value加入Map
            if (judge == userRoleList.size())
                userIdRoleIdMap.put(userId, roleIds);
        }

        for (SysUser sysUser : list) {
            HashSet<Long> roles = userIdRoleIdMap.get(sysUser.getUserId());
            sysUser.setRoleIds(roles != null ? roles.toArray(new Long[0]) : new Long[0]);
        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:export")
    @PostMapping(value="/export", produces = "application/octet-stream")
    @ApiOperation("导出用户数据")
    public void export(HttpServletResponse response, UserListVo vo) throws IOException {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo, user);
        List<SysUser> list = userService.selectUserList(user);
        com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser> util = new com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:import")
    @PostMapping("/importData")
    @ApiOperation("导入用户数据")
    public com.ruoyi.common.core.web.domain.AjaxResult importData(UserImportDataVo vo) throws Exception {
        boolean updateSupport = false;
        com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser> util = new com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(vo.getFile().getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return com.ruoyi.common.core.web.domain.AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser> util = new com.ruoyi.common.core.utils.poi.ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    @ApiOperation("获取当前登录用户信息,(username-用户账号名-String-必填)")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);

        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        return reUsingService.getUserLoginInfo(sysUser);
    }

    /**
     * 注册用户信息
     */
    @PostMapping("/register")
    @ApiOperation("注册用户信息")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    @ApiOperation("获取当前登录用户信息")
    public com.ruoyi.common.core.web.domain.AjaxResult getInfo() {

        return com.ruoyi.common.core.web.domain.AjaxResult.success(tokenService.getLoginUser());
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    @ApiOperation("根据用户编号获取详细信息,(userId-用户ID-Long-非必填)")
    public com.ruoyi.common.core.web.domain.AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        com.ruoyi.common.core.web.domain.AjaxResult ajax = com.ruoyi.common.core.web.domain.AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            ajax.put(com.ruoyi.common.core.web.domain.AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 根据用户编号获取用户基本信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:query")
    @GetMapping("/getUserById/{userId}")
    public com.ruoyi.common.core.web.domain.AjaxResult getUserById(@PathVariable("userId") Long userId) {
        return com.ruoyi.common.core.web.domain.AjaxResult.success(userService.getById(userId));
    }

  //  @GetMapping("/getUserById/{userId}")
    public R<SysUser> getUserByIdR(Long userId) {
        return R.ok(userService.getById(userId));
    }

    /**
     * 新增用户
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增用户")
    public com.ruoyi.common.core.web.domain.AjaxResult add(@Validated @RequestBody UserAddVo vo) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(vo, user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        } else if (vo.getPhonenumber().length() > 11) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("手机号码长度最多为11位！");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改用户")
    //  @D@S("master")
    public com.ruoyi.common.core.web.domain.AjaxResult edit(@Validated @RequestBody UserEditVo vo) {
        SysUser user = userService.getById(vo.getUserId());
        BeanUtils.copyProperties(vo, user);
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(vo.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("手机号码已存在");
        }
        if (StringUtils.isNotEmpty(vo.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && StringUtils.isEmpty(user.getUserName())) {
            user.setUserName(user.getPhonenumber());
            user.setPassword(SecurityUtils.encryptPassword(user.getPhonenumber()));
        }
        user.setRoleIds(user.getRoleIds());
        updateUserAndRole(user);
        List<SysRole> roles = new ArrayList<>();
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        if (user.getRoleIds().length > 0) {
            wrapper.in(SysRole.ROLE_ID, Sets.newHashSet(user.getRoleIds()));
            roles = roleService.list(wrapper);
        }

        if (SecurityUtils.getUserId().equals(user.getUserId())) {
            LoginUser loginUser = tokenService.getLoginUser();
            user.setRoles(roles);
            loginUser.setSysDept(deptService.selectDeptById(user.getDeptId()));
            loginUser.setSysUser(user);
            loginUser.setRoleIds(Sets.newHashSet(user.getRoleIds()));
            tokenService.refreshToken(loginUser);
            //user.setStatus("1");
        }
        userService.updateById(user);
        UpdateWrapper<AsmsAssetFullInfo> updateWrapper = new UpdateWrapper<AsmsAssetFullInfo>()
                .set(AsmsAssetFullInfo.NICK_NAME, vo.getNickName())
                .set(AsmsAssetFullInfo.PHONENUMBER, vo.getPhonenumber())
                .eq(AsmsAssetFullInfo.USER_ID, vo.getUserId());
        reUsingService.updateFullInfo(updateWrapper);

        return com.ruoyi.common.core.web.domain.AjaxResult.success("操作成功！");
    }

    /**
     * 删除用户(支持批量删除)
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @ApiOperation("删除用户(支持批量删除),(userIds-用户id数组-Long[]-必填)")
    public com.ruoyi.common.core.web.domain.AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    @ApiOperation("重置密码")
    public com.ruoyi.common.core.web.domain.AjaxResult resetPwd(@RequestBody UserResetPwdVo vo) {
        SysUser user = new SysUser();
        user.setUserId(vo.getUserId());
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(vo.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation("状态修改")
    public com.ruoyi.common.core.web.domain.AjaxResult changeStatus(@RequestBody UserChangeStatusVo vo) {
        SysUser user = new SysUser();
        user.setUserId(vo.getUserId());
        user.setStatus(vo.getStatus());
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:query")
    @GetMapping("/authRole/{userId}")
    @ApiOperation("根据用户ID获取授权角色,(userId-用户ID-Long-必填)")
    public com.ruoyi.common.core.web.domain.AjaxResult authRole(@PathVariable("userId") Long userId) {
        com.ruoyi.common.core.web.domain.AjaxResult ajax = com.ruoyi.common.core.web.domain.AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @ApiOperation("用户授权角色")
    public com.ruoyi.common.core.web.domain.AjaxResult insertAuthRole(UserInsertAuthRoleVo vo) {
        userService.insertUserAuth(vo.getUserId(), vo.getRoleIds());
        return success();
    }

    /**
     * 获取部门用户列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/deptUserList")
    @ApiOperation("根据部门id获取部门用户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "deptId", value = "用户Id")})
    public com.ruoyi.common.core.web.domain.AjaxResult deptUserList(@RequestParam(value = "deptId", required = false) Long deptId) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if(deptId!=null){
            queryWrapper.eq(SysUser.DEPT_ID, deptId);
        }else {
            Set<Long> userOwnDeptIds = tokenService.getUserOwnDeptIds();
            if (!SysUser.isAdmin(SecurityUtils.getUserId()) && userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
                queryWrapper.in(SysUser.DEPT_ID, userOwnDeptIds);
            }
        }

        return com.ruoyi.common.core.web.domain.AjaxResult.success(userService.list(queryWrapper));
    }


    @ApiOperation("根据手机号、微信号、用户名称搜索临时开门权限用户")
    @PostMapping("/sreachUser")
    public com.ruoyi.common.core.web.page.TableDataInfo sreachUser(@RequestBody SreachUserVo vo) {
        startPage();
        List<SysUser> list = userService.list(new QueryWrapper<SysUser>().like(vo.getPhoneNumber() != null && !vo.getPhoneNumber().equals(""), SysUser.PHONENUMBER, vo.getPhoneNumber())
                .like(vo.getUserName() != null && !vo.getUserName().equals(""), SysUser.NICK_NAME, vo.getUserName()).eq(SysUser.STATUS, 0));
        List<SreachUserVo> vos = new LinkedList<>();

        if (list != null && list.size() > 0) {
            for (SysUser user : list) {
                SreachUserVo rVo = new SreachUserVo();
                rVo.setUserId(user.getUserId());
                rVo.setUserName(user.getNickName());
                rVo.setPhoneNumber(user.getPhonenumber());
                List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.DEPT_ID, user.getDeptId()));
                if (deptList != null && deptList.size() > 0) {
                    rVo.setDeptName(deptList.get(0).getDeptFullName());
                }
                vos.add(rVo);
            }
        }

        return getDataTable(vos);
    }

    /**
     * 根据openId获取或创建用户信息
     */
    @GetMapping("/getOrCreateUserByWxOpenId")
    @ApiOperation("根据openId获取或创建用户信息")
    public R<LoginUser> getOrCreateUserByWxOpenId(@RequestParam(value = "openId") String openId) {
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.WX_OPEN_ID, openId), false);
        if (user == null) {
            SysUser newUser = new SysUser();
            newUser.setWxOpenId(openId);
            newUser.setUserName("");
            newUser.setNickName("游客");
            newUser.setCreateTime(System.currentTimeMillis());
            userService.save(newUser);
            user = newUser;
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(5L);
            userRole.setCreateTime(System.currentTimeMillis());
            sysUserRoleService.save(userRole);
        }
        return reUsingService.getUserLoginInfo(user);
    }

    @GetMapping("/getUserListByIds")
    public R<Map<Long, SysUser>> getUserListByIds(@RequestParam(value = "ids", required = true) Long[] ids) {
        Map<Long, SysUser> map = new HashMap<>();
        if (ids == null || ids.length == 0) {
            return R.ok(map);
        }
        List<SysUser> list = userService.list(new QueryWrapper<SysUser>().in(SysUser.USER_ID, Arrays.asList(ids)));

        for (SysUser user : list) {
            map.put(user.getUserId(), user);
        }
        return R.ok(map);
    }

  //  @SneakyThrows
    @ApiOperation("小程序一键获取手机号")
    @GetMapping("/getWxUserPhone")
    public com.ruoyi.common.core.web.domain.AjaxResult getWxUserPhone(@RequestParam("encryptedData") String encryptedData,
                                                                      @RequestParam("iv") String iv) {
        WxMaService maService = WxMaConfiguration.getMaService();

        WxMaPhoneNumberInfo phoneNoInfo = maService.getUserService().getPhoneNoInfo(tokenService.getLoginUser().getSessionKey(), encryptedData, iv);
        SysUser wxUser = tokenService.getLoginUser().getSysUser();
        if (phoneNoInfo.getPhoneNumber().equals(wxUser.getPhonenumber())) {
            //手机号码一样
            return com.ruoyi.common.core.web.domain.AjaxResult.success(reUsingService.getUserLoginInfo(wxUser).getData().getSysUser().getPhonenumber());
        }
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.PHONENUMBER, phoneNoInfo.getPhoneNumber()), false);
        if (user == null) {
            //系统没有手机号
            return com.ruoyi.common.core.web.domain.AjaxResult.success(phoneNoInfo.getPhoneNumber());
        } else {
            //系统有手机号
            user.setWxOpenId(wxUser.getWxOpenId());
            user.setUpdateTime(System.currentTimeMillis());
            //重置已有微信账号信息，把微信标识转移到手机号对应账号
            wxUser.setWxOpenId("");
            wxUser.setUpdateTime(System.currentTimeMillis());
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq(SysUserRole.USER_ID, wxUser.getUserId()));
            userService.updateBatchById(Lists.newArrayList(user, wxUser));
            LoginUser loginUser = reUsingService.getUserLoginInfo(user).getData();
            return com.ruoyi.common.core.web.domain.AjaxResult.success(loginUser.getSysUser().getPhonenumber());
        }
    }

  //  @SneakyThrows
    @PostMapping("/updateUserAndRole")
    @Transactional
    public R updateUserAndRole(@RequestBody SysUser sysUser) {
        if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !sysUser.getPhonenumber()
                .equals(userService.selectUserById(sysUser.getUserId()).getPhonenumber()) &&
                UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            return R.fail("手机号码已存在!");
        }
        if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && StringUtils.isEmpty(sysUser.getUserName())) {
            sysUser.setUserName(sysUser.getPhonenumber());
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPhonenumber()));
        }
        userService.updateById(sysUser);
        // 如果修改了角色，则先删除所有用户角色关系数据，然后在批量添加用户角色关系数据
        List<SysUserRole> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.USER_ID, sysUser.getUserId()));
        HashSet<Long> set = new HashSet<>();
        userRoleList.forEach(item -> set.add(item.getRoleId()));
        Long[] a = set.toArray(new Long[0]);
        Long[] b = sysUser.getRoleIds();
        Arrays.sort(a);
        Arrays.sort(b);
        if (! Arrays.equals(a, b)) {
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq(SysUserRole.USER_ID, sysUser.getUserId()));
            List<SysUserRole> userRoles = new ArrayList<>();
            for (Long roleId : sysUser.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(roleId);
                userRole.setCreateBy(sysUser.getNickName());
                userRole.setCreateTime(System.currentTimeMillis());
                userRoles.add(userRole);
            }
            sysUserRoleService.saveBatch(userRoles);
        }

        return R.ok();
    }

    @GetMapping("/getOwnDeptCharger")
    public R<List<SysUser>> getOwnDeptCharger(@RequestParam("deptId") Long deptId) {

        QueryWrapper<SysUser> queryWrapper = getUserListByRoleKeyAndDeptIds("oCharger", Sets.newHashSet(deptId), null);
        if(queryWrapper==null)return R.ok(new ArrayList<>());
        return R.ok(userService.list(queryWrapper));
    }

    @GetMapping("/getMDeptCharger")
    public R<List<SysUser>> getMDeptCharger(@RequestParam("deptId") Long deptId) {

        QueryWrapper<SysUser> queryWrapper = getUserListByRoleKeyAndDeptIds("mCharger", Sets.newHashSet(deptId), null);
        if(queryWrapper==null)return R.ok(new ArrayList<>());
        return R.ok(userService.list(queryWrapper));
    }

    @GetMapping("/getIDeptCharger")
    public R<List<SysUser>> getIDeptCharger(@RequestParam("deptId") Long deptId) {

        QueryWrapper<SysUser> queryWrapper = getUserListByRoleKeyAndDeptIds("iCharger", Sets.newHashSet(deptId), null);
        if(queryWrapper==null)return R.ok(new ArrayList<>());
        return R.ok(userService.list(queryWrapper));
    }

    @ApiOperation("获取巡检人员列表")
    @GetMapping("/getInspectorList")
    public R<List<SysUser>> getInspectorList() {
        QueryWrapper<SysUser> queryWrapper = getUserListByRoleKeyAndDeptIds("iInspector", tokenService.getLoginUser().getDeptIds(), null);
        if(queryWrapper==null)return R.ok(new ArrayList<>());
        return R.ok(userService.list(queryWrapper));
    }

    @ApiOperation("获取售后维护部门安装人员列表")
    @GetMapping("/getInstallerList")
    public R<List<SysUser>> getInstallerList(@RequestParam(value = "deptId",required = false) Long deptId) {
        Set<Long> deptIds = new HashSet<>();
        if(deptId == null){
            deptIds = tokenService.getLoginUser().getDeptIds();
        }else{
            deptIds.add(deptId);
        }
        QueryWrapper<SysUser> queryWrapper = getUserListByRoleKeyAndDeptIds("mInstaller",deptIds, null);

        if(queryWrapper == null){
            return R.ok();
        }
        return R.ok(userService.list(queryWrapper));
    }

    private QueryWrapper<SysUser> getUserListByRoleKeyAndDeptIds(String roleKey, Set<Long> deptIds, GetMaintenanceUsersVo vo) {
        List<SysRole> roles = roleService.list(new QueryWrapper<SysRole>()
                .in(SysRole.DEPT_ID, deptIds).eq(SysRole.ROLE_KEY, roleKey).select(SysRole.ROLE_ID));
        if (roles.size() == 0) {
            return null;
        }
        Set<Long> roleIds = new HashSet<>();
        roles.forEach(item -> roleIds.add(item.getRoleId()));
        if (roleIds.size() == 0) {
            return null;
        }
        List<SysUserRole> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>()
                .in(SysUserRole.ROLE_ID, roleIds));
        HashSet<Long> userIds = new HashSet<>();
        for (SysUserRole userRole : userRoleList) {
            userIds.add(userRole.getUserId());
        }

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (userIds.size() == 0) {
            return null;
        }
        queryWrapper.in(SysUser.USER_ID, userIds);


        if (vo != null && vo.getUserName() != null) {
            queryWrapper.like(SysUser.NICK_NAME, vo.getUserName());
        }

        if (vo != null && vo.getPhonenumber() != null) {
            queryWrapper.like(SysUser.PHONENUMBER, vo.getPhonenumber());
        }
        return queryWrapper;
    }

    @PostMapping("/getUserNameById")
    public R<HashMap<Long, String>> getUserNameByIds(@RequestParam("userIds") Long[] userIds) {

        if (userIds == null || userIds.length < 1) {
            return R.ok(null);
        }
        return R.ok(userService.getUserNameByIds(userIds));
    }

    @PostMapping("/getDeptManegerByDeptId")
    public R<SysUser> getDeptManegerByDeptId(@RequestParam("deptId") Long deptId) {
        List<SysUser> sysUsers = userService.getDeptManegerByDeptId(deptId);

        if (sysUsers.size() > 0) {
            return R.ok(sysUsers.get(0));
        } else {
            return R.fail("负责人信息获取失败！");
        }
    }

    @PostMapping("/getDeptManegersByDeptId")
    public R<List<SysUser>> getDeptManegersByDeptId(@RequestParam("deptId") Long deptId) {
        List<SysUser> sysUsers = userService.getDeptManegerByDeptId(deptId);

        if (sysUsers.size() > 0) {
            return R.ok(sysUsers);
        } else {
            return R.fail("负责人信息获取失败！");
        }
    }

    @PostMapping("/getDeptManegersByDeptIds")
    public R<List<SysUser>> getDeptManegersByDeptIds(@RequestBody List<Long> deptIds) {
        List<SysUser> allUsers = new LinkedList<>();

        for (Long deptId : deptIds) {
            List<SysUser> sysUsers = userService.getDeptManegerByDeptId(deptId);
            allUsers.addAll(sysUsers);
        }

        if (allUsers.size() > 0) {
            return R.ok(allUsers);
        } else {
            return R.fail("负责人信息获取失败！");
        }
    }

    @PostMapping("/getDeptManegersByDeptIdAndRoles")
    public R<List<SysUser>> getMaintenanceDeptManegersByDeptIds(@RequestBody List<Long> deptIds) {
        List<SysUser> allUsers = new LinkedList<>();

        for (Long deptId : deptIds) {
            List<SysUser> sysUsers = userService.getMaintenanceDeptManegersByDeptIds(deptId);
            allUsers.addAll(sysUsers);
        }

        if (allUsers.size() > 0) {
            return R.ok(allUsers);
        } else {
            return R.fail("负责人信息获取失败！");
        }
    }

    @PostMapping("/getUserNameDeptNameByUserId")
    public R<HashMap<Long, UserDeptName>> getUserNameDeptNameByUserId(@RequestBody List<Long> userIds) {
        return R.ok(userService.getUserNameDeptNameByUserId(userIds));
    }

    @ApiOperation(value = "获取维修人员列表", response = MaintenanceUsersVo.class)
    @GetMapping("/getMaintenanceUsers")
    public com.ruoyi.common.core.web.page.TableDataInfo getMaintenanceUsers(GetMaintenanceUsersVo vo) {
        //获取维修人员列表
        List<MaintenanceUsersVo> result = new ArrayList<>();
        Set<Long> userMaintenanceDeptIds = tokenService.getUserMaintenanceDeptIds();
        if (userMaintenanceDeptIds == null || userMaintenanceDeptIds.size() == 0) {
            return getDataTable(result);
        }
        QueryWrapper<SysUser> wrapper = getUserListByRoleKeyAndDeptIds("mRepair", userMaintenanceDeptIds, vo);
        if (wrapper == null) {
            return getDataTable(result);
        }
        startPage();
        List<SysUser> userList = userService.list(wrapper);
        Set<Long> userIds = userList.stream().map(SysUser::getUserId).collect(Collectors.toSet());

        //获取维修人员剩余工单数量
        R<Map<Long, Integer>> resultR = faultAssetController.getRepairersWorkNum(userIds);
        if (resultR.getCode() == R.FAIL)
            throw new com.ruoyi.common.core.exception.ServiceException(resultR.getMsg());
        Map<Long, Integer> userWorkNumMap = resultR.getData();

        for (SysUser sysUser : userList) {
            MaintenanceUsersVo usersVo = new MaintenanceUsersVo();
            BeanUtils.copyProperties(sysUser, usersVo);
            Integer workNum = userWorkNumMap.get(sysUser.getUserId());
            usersVo.setWorkNum(workNum);
            usersVo.setStatus(workNum == 0 ? 0 : 1);
            result.add(usersVo);
        }
        return getDataTable(result);
    }

    @PreAuthorize
    @GetMapping("/frozenUser")
    @ApiOperation("冻结/解冻用户")
    public com.ruoyi.common.core.web.domain.AjaxResult frozenUser(@ApiParam(value = "用户ID", required = true) Long userId,
                                                                  @ApiParam(value = "帐号状态(0-解冻 1-冻结)", required = true) String status) {
        //先获取当前登录用户的角色
        Set<Long> roleIds = tokenService.getLoginUser().getRoleIds();
        boolean flag = false;
        for (Long roleId : roleIds) {
            if (roleId.equals(2L) || roleId.equals(4L)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("仅支持部门负责人和部门决策者操作员工！");
        }
        //修改用户状态
        userService.update(new UpdateWrapper<SysUser>().set(SysUser.STATUS, status).eq(SysUser.USER_ID, userId));
        return com.ruoyi.common.core.web.domain.AjaxResult.success("操作成功！");
    }

    @ApiOperation("获取在线用户列表")
    @GetMapping("/online/list")
    public com.ruoyi.common.core.web.page.TableDataInfo list(@ApiParam(value = "deptName") String deptName,
                                                             @ApiParam(value = "userName") String userName) {
        Collection<String> keys = redisService.keys(Constants.LOGIN_TOKEN_KEY + "*");

        List<OnlineUserVo> onlineUserList = new ArrayList<>();
        for (String key : keys) {
            LoginUser user = redisService.getCacheObject(key);
            if(user.getUserId() == 5623 || user.getUserId() == 4913){
                System.out.println(user);
            }else{
                System.out.println(user.getUserId());
            }
            if (user == null) continue;

            OnlineUserVo vo = new OnlineUserVo();
            vo.setTokenId(key);
            vo.setUserName(user.getUsername());
            vo.setDeptName(user.getSysDept().getDeptFullName());
            vo.setIpAddr(user.getIpaddr());
            vo.setLoginTime(user.getLoginTime());
            if (StringUtils.isNotEmpty(deptName) && StringUtils.isNotEmpty(userName)) {
                if (StringUtils.equals(vo.getDeptName(), deptName) &&
                        StringUtils.equals(vo.getUserName(), userName)) {
                    onlineUserList.add(vo);
                }
            } else if (StringUtils.isNotEmpty(deptName)) {
                if (StringUtils.equals(vo.getDeptName(), deptName)) {
                    onlineUserList.add(vo);
                }
            } else if (StringUtils.isNotEmpty(userName)) {
                if (StringUtils.equals(vo.getUserName(), userName)) {
                    onlineUserList.add(vo);
                }
            } else {
                onlineUserList.add(vo);
            }
        }
        return getDataTable(onlineUserList);
    }

    /**
     * 强退用户
     */
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @GetMapping("/online/{tokenId}")
    public com.ruoyi.common.core.web.domain.AjaxResult forceLogout(@PathVariable String tokenId) {
        redisService.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId);
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    @PostMapping("/doImportDeptUserInfo")
    @PreAuthorize
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public R<ImportDeptUserInfoVo> doImportDeptUserInfo(@RequestBody DoImportDeptUserInfoVo vo, @RequestParam("xid") String xid) {

        Map<String, Object> deptMap = vo.getDeptMap();

        List<DeptUserVo> deptUserList = vo.getDeptUserList();

        Map<String, SysUser> users = new HashMap<>();
        for (DeptUserVo deptUserVo : deptUserList) {
            if(StringUtils.isNotEmpty(deptUserVo.getNickName())){
                SysUser user = new SysUser();
                Object object = deptMap.get(deptUserVo.getUDeptName());
                SysDept sysDept = JSONObject.parseObject(JSONObject.toJSONString(object), SysDept.class);
                user.setDeptId(sysDept.getDeptId());
                user.setPhonenumber(deptUserVo.getCellphone());
                user.setNickName(deptUserVo.getNickName());
                SysUser sysUser = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.PHONENUMBER, user.getPhonenumber()), false);
                if (sysUser == null) {
                    user.setUserName(user.getPhonenumber());

                    user.setCreateBy(SecurityUtils.getUsername());
                    user.setCreateTime(System.currentTimeMillis());
                    if(StringUtils.isNotEmpty(user.getPhonenumber())){
                        user.setPassword(SecurityUtils.encryptPassword(user.getPhonenumber()));
                    }

                    user.setNickName(deptUserVo.getNickName());
                    Long[] roleIds = new Long[]{6L};
                    user.setRoleIds(roleIds);
                    userService.insertUser(user);
                    users.put(user.getPhonenumber(), user);
                } else {
                    sysUser.setDeptId(user.getDeptId());
                    sysUser.setUpdateBy(SecurityUtils.getUsername());
                    sysUser.setUpdateTime(System.currentTimeMillis());
                    userService.updateById(sysUser);
                    users.put(sysUser.getPhonenumber(), sysUser);
                }
            }

        }
        ImportDeptUserInfoVo resultVo = new ImportDeptUserInfoVo();
        resultVo.setUsers(users);
        return R.ok(resultVo);
    }


    @PostMapping("/getMDeptsChargersNoticeInfo")
    public R<Map<Long, List<SysUserNoticeInfo>>> getMDeptsChargersNoticeInfo(@RequestBody Set<Long> deptIds) {
        return getDeptsChargersNoticeInfo(deptIds, "mCharger");
    }

    @PostMapping("/getODeptsChargersNoticeInfo")
    public R<Map<Long, List<SysUserNoticeInfo>>> getODeptsChargersNoticeInfo(@RequestBody Set<Long> deptIds) {
        return getDeptsChargersNoticeInfo(deptIds, "oCharger");
    }

    @PostMapping("/getUsersNoticeInfo")
    public R<List<SysUserNoticeInfo>> getUsersNoticeInfo(@RequestBody Set<Long> userIds) {
        List<SysUserNoticeInfo> userNoticeInfos = new ArrayList<>();
        if (userIds == null || userIds.size() == 0) {
            return R.ok(userNoticeInfos);
        }
        Map<Long, String> userNotifyInfo = getUserNotifyInfo(userIds);
        List<SysUser> list = userService.list(new QueryWrapper<SysUser>().in(SysUser.USER_ID, userIds));
        list.forEach(item -> {
            SysUserNoticeInfo noticeInfo = new SysUserNoticeInfo();
            BeanUtils.copyProperties(item, noticeInfo);
            noticeInfo.setNotifyTypeIds(userNotifyInfo.get(item.getUserId()));
            userNoticeInfos.add(noticeInfo);
        });
        return R.ok(userNoticeInfos);
    }

    @PostMapping("/testACID")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public R testACID(@RequestBody SysUser user) {

        userService.update(new UpdateWrapper<SysUser>().eq(SysUser.USER_ID, user.getUserId()).set(SysUser.NICK_NAME, user.getNickName()));
        return R.ok();
    }

    private Map<Long, String> getUserNotifyInfo(Set<Long> userIds) {

        Map<Long, String> resultMap = new HashMap<>();

        List<SysNotify> list = notifyService.list(new QueryWrapper<SysNotify>().in(SysNotify.SYS_USER_ID, userIds));
        if (list.size() > 0) {
            list.forEach(item -> resultMap.put(item.getSysUserId(), item.getNotifyTypeIds()));
        }
        return resultMap;

    }

    private Map<Long, List<SysUserNoticeInfo>> getDeptUserNotifyInfosByUserList(List<SysUser> users) {
        Map<Long, List<SysUserNoticeInfo>> resultMap = new HashMap<>();
        Set<Long> userIds = new HashSet<>();
        users.forEach(item -> userIds.add(item.getUserId()));
        Map<Long, String> userNotifyInfo = getUserNotifyInfo(userIds);
        users.forEach(item -> {
            SysUserNoticeInfo noticeInfo = new SysUserNoticeInfo();
            BeanUtils.copyProperties(item, noticeInfo);
            noticeInfo.setNotifyTypeIds(userNotifyInfo.get(item.getUserId()));
            resultMap.merge(item.getDeptId(), Lists.newArrayList(noticeInfo), (o, n) -> {
                        n.addAll(o);
                        return o;
                    }
            );
        });
        return resultMap;
    }

    private R<Map<Long, List<SysUserNoticeInfo>>> getDeptsChargersNoticeInfo(Set<Long> deptIds, String roleKey) {
        Map<Long, List<SysUserNoticeInfo>> resultMap = new HashMap<>();
        if (deptIds == null || deptIds.size() == 0) {
            return R.ok(resultMap);
        }
        List<SysUser> mChargers = userService.list(getUserListByRoleKeyAndDeptIds(roleKey, deptIds, null));
        if (mChargers.size() == 0) {
            return R.ok(resultMap);
        }
        return R.ok(getDeptUserNotifyInfosByUserList(mChargers));
    }

    /**
     * 添加人脸标识
     *
     * @param userId
     * @param faceToken
     * @return
     */
    @GetMapping("/addFaceToken")
    public com.ruoyi.common.core.web.domain.AjaxResult addFaceToken(@RequestParam("userId") Long userId, @RequestParam("faceToken") String faceToken) {
        userService.update(new UpdateWrapper<SysUser>().set(SysUser.FACE_TOKEN, faceToken).eq(SysUser.USER_ID, userId));
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    /**
     * 根据deptId获取维护人员列表
     */
    @GetMapping("/getMUserByDeptId")
    public R<List<SysUser>> getMUserByDeptId(@RequestParam("deptId") Long deptId) {
        return R.ok(userService.list(new QueryWrapper<SysUser>().eq(SysUser.DEPT_ID, deptId)));
    }

    /**
     * 根据deptId获取巡检部门的巡检人员列表
     */
    @GetMapping("/getInspectionUsersByDeptId")
    public R<List<SysUser>> getInspectionUsersByDeptId(@RequestParam("deptId") Long deptId) {
        SysRole role = roleService.getOne(new QueryWrapper<SysRole>().eq(SysRole.DEPT_ID, deptId)
                .eq(SysRole.ROLE_KEY, "iInspector"));
        List<SysUserRole> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.ROLE_ID, role.getRoleId()));
        HashSet<Long> userIds = new HashSet<>();
        userRoleList.forEach(item -> userIds.add(item.getUserId()));
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (userIds.size() != 0) {
            wrapper.in(SysUser.USER_ID, userIds);
        } else {
            return R.ok(new ArrayList<>());
        }
        return R.ok(userService.list(wrapper));
    }

    @PostMapping("/import")
    //@Transactional
    public com.ruoyi.common.core.web.domain.AjaxResult importData(MultipartFile file) {
        com.ruoyi.common.core.utils.poi.ExcelUtil<ImportUserVo> util = new com.ruoyi.common.core.utils.poi.ExcelUtil<ImportUserVo>(ImportUserVo.class);
        List<ImportUserVo> list = null;
        try {
            list = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return com.ruoyi.common.core.web.domain.AjaxResult.error("解析Excel出现错误，请确定数据是否为空并是否按照要求填写！");
        }
        Set<String> phones =new HashSet<>();
        Set<String> deptNames =new HashSet<>();
        Set<String> openIds =new HashSet<>();
        for (ImportUserVo importUserVo : list) {
            if(StringUtils.isNotEmpty(importUserVo.getPhonenumber())){
                phones.add(importUserVo.getPhonenumber());
            }
            if(StringUtils.isNotEmpty(importUserVo.getDeptName())){
                deptNames.add(importUserVo.getDeptName());
            }
            if(StringUtils.isNotEmpty(importUserVo.getWxOpenId())){
                openIds.add(importUserVo.getWxOpenId());
            }
        }
        Map<String, SysUser> userMap =new HashMap<>();
        Map<String, SysDept> deptMap =new HashMap<>();

        List<SysUser> hasUsers = userService.list(new QueryWrapper<SysUser>().in(SysUser.PHONENUMBER, phones));
        List<SysUser> hasUsers2 = userService.list(new QueryWrapper<SysUser>().in(SysUser.WX_OPEN_ID, openIds));
        List<SysDept> depts =deptService.list(new QueryWrapper<SysDept>().in(SysDept.DEPT_FULL_NAME,deptNames));

        hasUsers.forEach(item->userMap.put(item.getPhonenumber(),item));
        hasUsers2.forEach(item->userMap.put(item.getWxOpenId(),item));
        depts.forEach(item->deptMap.put(item.getDeptFullName(),item));
        List<SysUser> saveUsers =new ArrayList<>();
        List<SysUser> editUsers =new ArrayList<>();
        Map<Long,List<SysRole>> deptRoles =new HashMap<>();
        for (ImportUserVo importUserVo : list) {

            SysDept dept = deptMap.get(importUserVo.getDeptName());
            SysUser hasUser = userMap.get(importUserVo.getWxOpenId());
            if(hasUser==null){
                hasUser=userMap.get(importUserVo.getPhonenumber());
            }
            List<SysRole> roles =new ArrayList<>();
            if(dept!=null){
                if(deptRoles.get(dept.getDeptId())==null){
                    roles =roleService.list(new QueryWrapper<SysRole>().like(SysRole.ROLE_KEY,"Member").eq(SysRole.DEPT_ID,dept.getDeptId()));
                    deptRoles.put(dept.getDeptId(),roles);
                }
                else roles = deptRoles.get(dept.getDeptId());
            }
            if (hasUser == null) {
                SysUser addUser =new SysUser();
                BeanUtils.copyProperties(importUserVo,addUser);
                if(StringUtils.isNotEmpty(addUser.getPhonenumber())){
                    addUser.setUserName(addUser.getPhonenumber());
                    addUser.setPassword(SecurityUtils.encryptPassword(addUser.getPhonenumber()));
                }else {
                    String string = getRandomString(8);
                    addUser.setUserName(string);
                    addUser.setPassword(SecurityUtils.encryptPassword(string));
                }
                if(dept!=null){
                    addUser.setDeptId(dept.getDeptId());
                    addUser.setRoleIds( roles.stream().map(SysRole::getRoleId).distinct().toArray(Long[]::new));
                }else {
                    doAddDept(addUser,importUserVo,deptMap,deptRoles);
                }
                saveUsers.add(addUser);
                //userService.insertUser(addUser);
            }else {
                BeanUtils.copyProperties(importUserVo,hasUser);
                if(dept!=null){
                    hasUser.setRoleIds( roles.stream().map(SysRole::getRoleId).distinct().toArray(Long[]::new));
                    hasUser.setDeptId(dept.getDeptId());
                }else {
                    doAddDept(hasUser,importUserVo,deptMap,deptRoles);
                }
                //userService.updateUser(hasUser);
                editUsers.add(hasUser);
            }
        }
        userService.saveBatch(saveUsers);

        userService.updateBatchById(editUsers);
        Set<Long> editUserIds =new HashSet<>();
        editUsers.forEach(item->editUserIds.add(item.getUserId()));
        if (editUserIds.size()>0){
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in(SysUserRole.USER_ID,editUserIds));
        }

        List<SysUserRole> userRoles =new ArrayList<>();

        saveUsers.addAll(editUsers);
        saveUsers.forEach(item->{
            for (Long roleId : item.getRoleIds()) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(item.getUserId());
                ur.setRoleId(roleId);
                userRoles.add(ur);
            }
        });
        sysUserRoleService.saveBatch(userRoles);
        return success();
    }

    private void doAddDept(SysUser addUser, ImportUserVo importUserVo, Map<String, SysDept> deptMap, Map<Long,List<SysRole>> deptRoles) {
        if(StringUtils.isEmpty(importUserVo.getDeptName())){
            addUser.setRoleIds(new Long[]{5L});
            return;
        }
        //新增部门
        SysDept sysDept = new SysDept();
        sysDept.setCreateBy(SecurityUtils.getUsername());
        sysDept.setCreateTime(System.currentTimeMillis());
        sysDept.setParentId(0L);
        sysDept.setDeptFullName(importUserVo.getDeptName());
        sysDept.setDeptShortName(importUserVo.getDeptName());
        sysDept.setAncestors("0");
        deptService.save(sysDept);
        deptMap.put(sysDept.getDeptFullName(),sysDept);
        //新增部门后向角色表加入部门对应的角色数据
        String[] deptTypes = {"0","1","2"};
        List<SysRole> newRoles = deptService.addRoleInfo(deptTypes, sysDept.getDeptId());
        deptRoles.put(sysDept.getDeptId(),newRoles);
        addUser.setRoleIds( newRoles.stream().map(SysRole::getRoleId).distinct().toArray(Long[]::new));
        addUser.setDeptId(sysDept.getDeptId());
    }

    @PostMapping("/getUserByOpenIds")
    public R<Map<String, SysUser>> getUserByOpenIds(@RequestBody Set<String> openIds){
        Map<String, SysUser> resultMap =new HashMap<>();

        List<SysUser> list = userService.list(new QueryWrapper<SysUser>().in(SysUser.WX_OPEN_ID, openIds));
        list.forEach(item->resultMap.put(item.getWxOpenId(),item));
        return R.ok(resultMap);
    }

    public String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    @PreAuthorize
    @ApiOperation("获取某部门的所有维修人员")
    @GetMapping("/getMUsersByDeptId")
    public com.ruoyi.common.core.web.domain.AjaxResult getMUsersByDeptId(@RequestParam("deptId") Long deptId) {
        List<KeyValueVo> result = new ArrayList<>();
        //获取某机构的维修人员角色
        SysRole role = roleService.getOne(new QueryWrapper<SysRole>()
                .eq(SysRole.DEPT_ID, deptId).eq(SysRole.ROLE_KEY, "mRepair"), false);
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        if (role != null) {
            wrapper.eq(SysUserRole.ROLE_ID, role.getRoleId());
        } else {
            return com.ruoyi.common.core.web.domain.AjaxResult.success(result);
        }
        //获取维修人员
        List<SysUserRole> userRoleList = sysUserRoleService.list(wrapper);
        HashSet<Long> userIds = new HashSet<>();
        if (userRoleList != null) {
            userRoleList.forEach(item -> userIds.add(item.getUserId()));
        } else {
            return com.ruoyi.common.core.web.domain.AjaxResult.success(result);
        }
        QueryWrapper<SysUser> wrapper1 = new QueryWrapper<>();
        if (userIds.size() > 0) {
            wrapper1.in(SysUser.USER_ID, userIds);
        } else {
            return com.ruoyi.common.core.web.domain.AjaxResult.success(result);
        }
        List<SysUser> userList = userService.list(wrapper1);
        userList.forEach(item -> {
            KeyValueVo vo = new KeyValueVo();
            vo.setKey(item.getUserId());
            vo.setValue(item.getNickName());
            result.add(vo);
        });
        return com.ruoyi.common.core.web.domain.AjaxResult.success(result);
    }

    /**
     * 通过用户姓名查询用户
     * @param nickName 用户姓名
     * @return 用户ID集合
     */
    @GetMapping("/getUserByNickName")
    public R<HashSet<Long>> getUserByNickName(@RequestParam("nickName") String nickName) {
        HashSet<Long> userIds = new HashSet<>();
        List<SysUser> userList = userService.list(new QueryWrapper<SysUser>()
                .like(SysUser.NICK_NAME, nickName));
        if (userList != null) {
            userList.forEach(user -> userIds.add(user.getUserId()));
        }
        return R.ok(userIds);
    }

    /**
     * 获取系统中所有的用户
     * @return 用户id与用户角色对应管理的Map
     */
    @GetMapping("/getAllUsers")
    public R<Map<Long, SysUser>> getAllUsers() {
        HashMap<Long, SysUser> map = new HashMap<>();
        List<SysUser> list = userService.list();
        if (list != null){
            list.forEach(user -> map.put(user.getUserId(), user));
        }
        return R.ok(map);
    }

    @GetMapping("/saveOrGetUser")
    public R<SysUser> saveOrGetUser(@RequestParam("institutionName") String institutionName, @RequestParam("phonenumber") String phonenumber,
                                    @RequestParam("nickName") String nickName, @RequestParam("wxOpenId") String wxOpenId){
        SysDept dept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_SHORT_NAME,institutionName));
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.WX_OPEN_ID,wxOpenId).or().eq(SysUser.PHONENUMBER,phonenumber),false);

        if(user!=null){
            if(user.getDeptId()==null){
                user.setDeptId(dept.getDeptId());
                userService.updateById(user);
            }
            return R.ok(user);
        }
        SysUser addUser =new SysUser();
        addUser.setWxOpenId(wxOpenId);
        addUser.setUserName(phonenumber);
        addUser.setPhonenumber(phonenumber);
        addUser.setDeptId(dept.getDeptId());
        addUser.setNickName(nickName);
        addUser.setCreateTime(System.currentTimeMillis());
        userService.save(addUser);
        return R.ok(addUser);
    }

    @GetMapping("/getResovlersByDeptId")
    public R<List<SysUser>> getResovlersByDeptId(@RequestParam("deptId") Long deptId) {
        List<SysUser> resovlers = new ArrayList<>();
        SysRole sysRole = roleService.getOne(new QueryWrapper<SysRole>()
                .eq(SysRole.DEPT_ID, deptId).eq(SysRole.ROLE_KEY, "mRepair"), false);
        List<SysUserRole> roleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.ROLE_ID, sysRole.getRoleId()));
        HashSet<Long> userIds = new HashSet<>();
        roleList.forEach(item -> userIds.add(item.getUserId()));
        if (userIds.size() == 0)
            return R.ok(resovlers);

        return R.ok(userService.list(new QueryWrapper<SysUser>().in(SysUser.USER_ID, userIds)));
    }

    @GetMapping("/testInsertUserRole")
    public void testInsertUserRole() {

        //12191
        List<SysUser> list1 = userService.list(new QueryWrapper<SysUser>().eq(SysUser.DEPT_ID, 764));
        Set<Long> userIds =new HashSet<>();
        list1.forEach(item->userIds.add(item.getUserId()));

        List<SysUserRole> list2 = sysUserRoleService.list(new QueryWrapper<SysUserRole>().in(SysUserRole.USER_ID, userIds));
        Map<Long,List<SysUserRole>> userIdRolesMap =new HashMap<>();
        list2.forEach(item -> {
            List<SysUserRole> lists = new ArrayList<>();
            if (userIdRolesMap.containsKey(item.getUserId())) {
                lists.addAll(userIdRolesMap.get(item.getUserId()));
            }
            lists.add(item);
            userIdRolesMap.put(item.getUserId(), lists);
        });
        List<SysUserRole> addUserRoles =new ArrayList<>();
        userIds.forEach(item->{
            if(  !userIdRolesMap.containsKey(item)){
                SysUserRole userRole =new SysUserRole();
                userRole.setUserId(item);//6676\6677\6678
                userRole.setRoleId(6676L);
                addUserRoles.add(userRole);
                SysUserRole userRole1 =new SysUserRole();
                userRole1.setUserId(item);//6676\6677\6678
                userRole1.setRoleId(6677L);
                addUserRoles.add(userRole1);
                SysUserRole userRole2 =new SysUserRole();
                userRole2.setUserId(item);//6676\6677\6678
                userRole2.setRoleId(6678L);
                addUserRoles.add(userRole2);
            }
        });
        sysUserRoleService.saveBatch(addUserRoles);
    }

    @ApiOperation("修改手机号码")
    @PostMapping("/updateTel")
    public com.ruoyi.common.core.web.domain.AjaxResult updateTel(@ApiParam("电话号码") String tel) {
        userService.update(new UpdateWrapper<SysUser>().set(SysUser.PHONENUMBER, tel)
                .eq(SysUser.USER_ID, SecurityUtils.getUserId()));
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    @ApiOperation("修改字体大小)")
    @PostMapping("/updateFontSize")
    public com.ruoyi.common.core.web.domain.AjaxResult updateFontSize(@ApiParam("标准模式传18、关怀模式传30") Integer size) {
        userService.update(new UpdateWrapper<SysUser>().set(SysUser.MP_FONT_SIZE, size)
                .eq(SysUser.USER_ID, SecurityUtils.getUserId()));
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    @ApiOperation("通过userId获取用户对象")
    @GetMapping("/getUserByUserId")
    public com.ruoyi.common.core.web.domain.AjaxResult getUserByUserId(@RequestParam("userId") Long userId) {
        return com.ruoyi.common.core.web.domain.AjaxResult.success(userService.getById(userId));
    }

    @PreAuthorize
    @GetMapping("/getUserTest")
    public com.ruoyi.common.core.web.domain.AjaxResult getUserTest(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        LoginUser loginUser1 = tokenService.getLoginUser();
        System.out.println(SecurityUtils.getLoginUser());
        return AjaxResult.success();
    }
}
